<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<textarea rows="20" cols="100" id="tarText"></textarea>
<br>
<button id="startBtn">开始</button>
<button id="sortByWord" >按字母排序</button>
<button id="sortByCount" >按频率排序</button>
<ul id="resultArea">

</ul>

<script src="script/jquery.min.js"></script>
<script>

    var fenciVo = null;

    function showResultArea(tarArr) {
        var tarStr = tarArr.map(function (item) {
            return `
                <li>${item[0]}--${item[1]}</li>
            `
        })
        $("#resultArea").html(tarStr);
    }

    function replaceNum(text) {
        return text.replace(/[0-9]/g, '');
    }

    function replaceDownLine(text) {
        return text.replace(/_/g,'')
    }

    function getOriWordArr(text){
        return text.match(/\b\w+\b/g);
    }
    function getWordArr(Arr){
        return Arr.filter(item=>item.length>1)
    }

    function getLowerWordArr(Arr){
        return Arr.map(item => item.toLowerCase())
    }

    function initFenciObj(fenciArr){
        var keyArray = new Set(fenciArr);
        let result = {};
        keyArray.forEach(key=>{
            result[key]=0
        })

        return result;
    }

    function countFenci(tarFenciArr){
        tarFenciArr.forEach(function (item) {
            fenciVo[item] = fenciVo[item] +1;
        })
        // return fenciVo;
    }

    $(function () {

        function sortBy(fn){
            return Object.entries(fenciVo).sort(fn)
        }
        

        $("#sortByWord").on("click",function () {
            var result = sortBy(function (entityA,entityB) {
                return entityA[0]-entityB[0]
            })
            showResultArea(result)
        })

        $("#sortByCount").on("click",function () {
            var result = sortBy(function (entityA,entityB) {
                return entityB[1]-entityA[1];
            })
            showResultArea(result)
        })


        

        $("#startBtn").on('click',fenciHandle);

        function fenciHandle() {
            var $tarText = $("#tarText");

            var allText = $tarText.val();
            if(!allText){
                alert('请输入文本');
                return;
            }
            var tarFenciArr =getLowerWordArr( //转为小写
                            getWordArr( //得到分词数组，去除a,a,b 这种无效单词
                                getOriWordArr( //初步得到分词词组
                                    replaceDownLine( //删除下划线
                                        replaceNum(allText) //去除数字
                                    )

                                )
                            ))
            fenciVo = initFenciObj(tarFenciArr);
            countFenci(tarFenciArr);


        }


    })
</script>
</body>
</html>